package tech.runchen.gz5055.oms.common.websocket;

import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zzj
 */
@Component
@Log4j2
@ServerEndpoint("/notice/{uid}")
public class WebSocketServer {

    private static AtomicInteger onlineSessionClientCount = new AtomicInteger(0);
    private static final ConcurrentHashMap<String, CopyOnWriteArraySet<Session>> onlineSessionClientMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(@PathParam("uid") String uid, Session session) {
        CopyOnWriteArraySet<Session> users = onlineSessionClientMap.get(uid);
        if (users == null) {
            synchronized (onlineSessionClientMap) {
                if (!onlineSessionClientMap.contains(uid)) {
                    users = new CopyOnWriteArraySet<>();
                    onlineSessionClientMap.put(uid, users);
                }
            }
        }
        users.add(session);
        onlineSessionClientCount.incrementAndGet();
        log.info("连接建立成功，当前在线数为：{}===》开始监听新链接：session_id = {} ，uid = {}。", onlineSessionClientCount, session.getId(), uid);
    }

    @OnClose
    public void onClose(@PathParam("uid") String uid, Session session) {
        CopyOnWriteArraySet<Session> copyOnWriteArraySet = onlineSessionClientMap.get(uid);
        if (!copyOnWriteArraySet.isEmpty()) {
            Object[] objects = copyOnWriteArraySet.toArray();
            for (Object object : objects) {
                if (object.equals(session)) {
                    onlineSessionClientMap.get(uid).remove(object);
                    if (onlineSessionClientMap.get(uid).isEmpty()) {
                        onlineSessionClientMap.remove(uid);
                    }
                }
            }
        }
        onlineSessionClientCount.decrementAndGet();
        log.info("连接关闭成功，当前在线数为：{} ==> 关闭该连接信息：session_id = {}， uid = {}。", onlineSessionClientCount, session.getId(), uid);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("服务端收到客户端消息 ==> session_id = {}，message = {}", session.getId(), message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("WebSocket发生错误，错误信息为：" + error.getMessage());
        error.printStackTrace();
    }

    private void sendToAll(String message) {
        onlineSessionClientMap.forEach((uid, users) -> {
            for (Session session : users) {
                session.getAsyncRemote().sendText(message);
            }
        });
    }

    public void sendToUid(String uid, String message) {
        CopyOnWriteArraySet<Session> users = onlineSessionClientMap.get(uid);
        if (users != null) {
            for (Session session : users) {
                session.getAsyncRemote().sendText(message);
            }
        }
    }

}
